import { useCallback, useEffect, useState } from 'react';
import { Table, Card, Button, InputNumber, Empty, message } from 'antd';
import { DeleteOutlined, ShoppingCartOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { deleteGoods, getCartListApi, updateGoods } from '@/api/shop';
import { useNavigate } from 'react-router-dom';

const Cart = () => {
  // 购物车数据
  const [cartItems, setCartItems] = useState<CartList[]>([]);

  const router = useNavigate();

  const getCartList = useCallback(async () => {
    const res = await getCartListApi({
      page: 1,
      limit: 100,
    });
    if (res.code === 200) {
      setCartItems(res.data.list);
    } else {
      message.error(res.message);
    }
  }, []);

  useEffect(() => {
    getCartList();
  }, [getCartList]);

  // 修改商品数量
  const handleQuantityChange = async (id: number, value: number | null) => {
    if (!value) return;
    const res = await updateGoods(id, {
      ...cartItems.find((item) => item.id === id)!,
      goods_count: value,
    });
    if (res.code === 200) {
      getCartList();
    }
  };

  // 删除
  const handleDelete = async (id: number) => {
    const res = await deleteGoods([id]);
    if (res.code === 200) {
      setCartItems(cartItems.filter((item) => item.id !== id));
      message.success('商品已移除');
      getCartList();
    } else {
      message.error(res.message);
    }
  };

  const handleCheckout = () => {
    message.success('正在跳转到结算页面...');
    // 这里添加结算逻辑
  };

  const columns: ColumnsType<CartList> = [
    {
      title: '商品信息',
      dataIndex: 'goods_name',
      key: 'goods_name',
      render: (text, record) => (
        <div className="flex items-center space-x-4">
          <div className="w-20 h-20 bg-gray-100 rounded-lg overflow-hidden">
            <img
              src={record.img}
              alt={text}
              className="w-full h-full object-cover"
              // onError={(e) => {
              //   const target = e.target as HTMLImageElement;
              //   target.src = 'https://via.placeholder.com/80?text=野生菌';
              // }}
            />
          </div>
          <div>
            <div className="font-medium text-gray-800">{text}</div>
            <div className="text-sm text-gray-500">商品编号: {record.goods_id}</div>
          </div>
        </div>
      ),
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      key: 'goods_price',
      render: (text) => <span className="text-gray-800">¥{text.toFixed(2)}</span>,
    },
    {
      title: '数量',
      dataIndex: 'goods_count',
      key: 'goods_count',
      render: (text, record) => (
        <InputNumber
          min={1}
          max={99}
          value={text}
          onChange={(value) => handleQuantityChange(record.id, value)}
          className="w-20"
        />
      ),
    },
    {
      title: '小计',
      dataIndex: 'goods_price',
      key: 'goods_price',
      render: (text, record) => (
        <span className="text-emerald-600 font-medium">
          ¥{(text * record.goods_count).toFixed(2)}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="text"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>
      ),
    },
  ];

  const totalAmount = cartItems.reduce((sum, item) => sum + item.goods_price * item.goods_count, 0);

  return (
    <div className="h-full bg-gray-50 py-8 px-4">
      <div className="max-w-6xl mx-auto">
        <Card className="shadow-md">
          <div className="flex items-center mb-6">
            <ShoppingCartOutlined className="text-2xl text-emerald-600 mr-2" />
            <span className="text-xl font-medium">我的购物车</span>
          </div>

          {cartItems.length > 0 ? (
            <>
              <Table
                columns={columns}
                dataSource={cartItems}
                pagination={false}
                rowKey="id"
                className="mb-6"
              />
              <div className="flex justify-between items-center border-t pt-4">
                <div className="text-gray-500">
                  共 <span className="text-emerald-600 font-medium">{cartItems.length}</span> 件商品
                </div>
                <div className="flex items-center space-x-8">
                  <div className="text-lg">
                    合计：
                    <span className="text-emerald-600 font-medium text-xl">
                      ¥{totalAmount.toFixed(2)}
                    </span>
                  </div>
                  <Button
                    type="primary"
                    size="large"
                    onClick={handleCheckout}
                    className="bg-emerald-600 hover:bg-emerald-700 border-none min-w-[120px]"
                  >
                    结算
                  </Button>
                </div>
              </div>
            </>
          ) : (
            <Empty
              description="购物车是空的"
              className="py-12"
            >
              <Button
                type="primary"
                className="bg-emerald-600 hover:bg-emerald-700 border-none"
                onClick={() => router('/business')}
              >
                去购物
              </Button>
            </Empty>
          )}
        </Card>
      </div>
    </div>
  );
};

export default Cart;
